#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QString>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port->setText("8899");
    setWindowTitle("服务器");
    //创建监听的服务器对象
    m_s = new QTcpServer(this);
    connect(ui->set_listen,&QPushButton::clicked , this  , &MainWindow::on_set_listen_clicked );
    connect(ui->send_message,&QPushButton::clicked , this , &MainWindow::on_send_message_clicked);

    connect(m_s , &QTcpServer::newConnection , this ,[=](){
        m_tcp = m_s->nextPendingConnection();

        m_status->setPixmap(QPixmap(":/pic/yes.png").scaled(20,20));   //检测到连接后换连接状态
        //检测是否可以接受数据
        connect(m_tcp , &QTcpSocket::readyRead , this ,[=](){
            QByteArray data =m_tcp->readAll();
            ui->record->append("客户端："+ data );
        });

        connect(m_tcp , &QTcpSocket::disconnected , this  , [=](){
            m_tcp->close();
            m_tcp->deleteLater();  //delete m_tcp
        });
    });
    //状态类
    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/pic/no.png").scaled(20,20));  //用scaled方法对图片进行缩放
    ui->statusbar->addWidget(new QLabel("连接状态："));
    ui->statusbar->addWidget(m_status);
}


void MainWindow::on_set_listen_clicked(){
    unsigned short port = ui->port->text().toUShort();
    m_s->listen(QHostAddress::Any , port);
    ui->set_listen->setDisabled(true);      //设置好端口后，让按钮不能用
}
void MainWindow::on_send_message_clicked(){
    QString message = ui->record_2->toPlainText();
    m_tcp->write(message.toUtf8());
    ui->record->append("服务器："+ message );
}

MainWindow::~MainWindow()
{
    delete ui;
}

